package uk.co.richardwkirk.parkrun.android.events.displays;

import java.util.ArrayList;

import uk.co.richardwkirk.parkrun.android.R;
import uk.co.richardwkirk.parkrun.android.events.RegionalEventGroup;
import uk.co.richardwkirk.parkrun.data.events.Event;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

public class EventSelectionExpandableAdapter extends BaseExpandableListAdapter {

	ArrayList<RegionalEventGroup> regionalEvents;
	Context context;

	public EventSelectionExpandableAdapter(Context ctxt, ArrayList<RegionalEventGroup> list) {
		this.regionalEvents = list;
		this.context = ctxt;
	}

	@Override
	public Object getChild(int groupPosition, int childPosition) {
		ArrayList<Event> eventList = regionalEvents.get(groupPosition).getEntries();
		return eventList.get(childPosition);
	}

	@Override
	public long getChildId(int groupPosition, int childPosition) {
		return ((Event)getChild(groupPosition, childPosition)).getId();
	}

	@Override
	public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {

		Event event = (Event) getChild(groupPosition, childPosition);
		if (convertView == null) {
			LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = infalInflater.inflate(R.layout.event_selection_row, null);
		}

		TextView sequence = (TextView) convertView.findViewById(R.id.event_name);
		sequence.setText(event.getFullName());
		
		return convertView;
	}

	@Override
	public int getChildrenCount(int groupPosition) {
		ArrayList<Event> eventList = regionalEvents.get(groupPosition).getEntries();
		return eventList.size();
	}

	@Override
	public Object getGroup(int groupPosition) {
		return regionalEvents.get(groupPosition);
	}

	@Override
	public int getGroupCount() {
		return regionalEvents.size();
	}

	@Override
	public long getGroupId(int groupPosition) {
		return groupPosition;
	}

	@Override
	public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
		RegionalEventGroup groupInfo = (RegionalEventGroup) getGroup(groupPosition);
		if (convertView == null) {
			LayoutInflater inf = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inf.inflate(R.layout.event_selection_group, null);
		}

		TextView heading = (TextView) convertView.findViewById(R.id.heading);
		heading.setText(groupInfo.getRegionName().trim());
		
		return convertView;
	}

	@Override
	public boolean hasStableIds() {
		return true;
	}

	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		return true;
	}

}
